<?php
YII::import('dao.bid.*');
YII::import('application.extensions.YiiMailer.YiiMailer');
Yii::import('dao.share.class.InviteEmail');
class RegisterController extends Controller{
	public $layout='//layouts/default';
	public $username;
	public function actionIndex(){
		if(!yii::app()->user->isGuest){
			header('location:'.Yii::app()->baseurl);
		}
		$this->breadcrumbs = array("Register");
		$customer=new Customer();
		$dao = new RegisterDao();
		
		if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
		{
			echo CActiveForm::validate($dao);
			Yii::app()->end();
		}
		if(!empty($_POST)){
		    $uniqid = $this->createUniqid();
			$dao->attributes=$_POST['RegisterDao'];
			$dao->created=time();
			$dao->status=1;
			$dao->avatar=Yii::app()->resource->path('')."/images/avatar/headimg1.jpg";
			$dao->ip=$_SERVER["REMOTE_ADDR"];
			$dao->birthday=strtotime($dao->birthday);
			$dao->refer=$uniqid;
			$data=$dao->attributes;
			$result=$dao->save();
			if($result){
			    //发送同步注册请求
			    $result_send=$this->sendCurl($dao->attributes,Yii::app()->params['egunner']."paregister.php");
			    Yii::app()->cache->set("regis", $result_send);
			    //confirm the register with refer should  add promo bid
			    /* $invite=new InviteEmail('register');
			    $invite->email=$_POST['RegisterDao']['email'];
			    if ($invite->validate()){
			        $invite->success();
			    } */
			    
				$customer_info=$customer->findAllByAttributes(array("email"=>$_POST['RegisterDao']['email']));
				$bid = new BidDao();
				$bid->customerId=$customer_info[0]->id;
				$bid->getBidModel('cash')->setBid(5,'Register');
				//发送邮件通知注册成功，赠送5个PROMO BID 
				// 时间，用户名，赠BID数量
    			$mailer = new YiiMailer();
        	    $mailer->setView('welcome');//调用模板
        	    $mailer->setData(array(
        	        'USER_NAME'=>$customer_info[0]->user_name,
        	        'PASSWORD'=>$_POST['RegisterDao']['password']
        	    ));//所需数据
        	    //发送到邮箱
        	    $mailer->AddAddress($customer_info[0]->email);//目标邮箱
                
        	    $mailer->Subject = Yii::t('demo', 'eGunner Registration Confirmation');//标题
        	    if(!$mailer->Send()) {
        	        echo "Mailer Error: " . $mailer->ErrorInfo;
        	    }        	    
//         	    $email_confirm=$this->check_email(array('username'=>$_POST['RegisterDao']['user_name']));
//         	    if($email_confirm){
//         	        $login_auth=new SysAuth();
//         	        $login_auth->id       =$dao->customer_id;
//         	        $login_auth->username = $dao->user_name;
//         	        $login_auth->status='register';
//         	        Yii::app()->user->register = true;
//         	        $loginplus=new LoginPlus();
//         	        $loginplus->Login($login_auth);
//         	    }else{
        	        Yii::app()->session['mail_user']=$_POST['RegisterDao']['user_name'];
        	        $this->redirect(Yii::app()->params['site_url']."/register/sendmail");
//         	    }
			}		
		}
		$states=State::model()->findAll('country_id=10');
		$this->render('index',array('model'=>$dao,'states'=> $states));
	}
	public function check_email($data){
	    $return=$this->sendCurl($data, Yii::app()->params['egunner']."check_email.php");
	    if($return['result']){
	        return true;
	    }else{
	        return false;
	    }
	}
	public function actionSendMail(){
	    $username=Yii::app()->session['mail_user'];
	    $this->render('sendmail',array('username'=>$username));
	}
	/**
	 * Egunner获取该用户状态
	 */
	public function actionGetMail(){
	    $data=$_REQUEST;
	    if(!empty($data)){
	        $url=Yii::app()->params['egunner']."pa_activate_account.php";
	        $return=$this->sendCurl($data,$url);
	        echo $return;
	           
	    }else{
	        echo "No Data!";
	    }
	    
	}
	/**
	 * 对象类型转换成数组方法
	 * @param obj $e
	 * @return void|array
	 */
    function objectToArray($e){
        $e=(array)$e;
        foreach($e as $k=>$v){
            if( gettype($v)=='resource' ) return;
            if( gettype($v)=='object' || gettype($v)=='array' )
                $e[$k]=(array)objectToArray($v);
        }
        return $e;
    }
	public function sendCurl($data,$url){
	    $ch = curl_init($url);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HEADER, 0 );
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	    /**
	     * 发送JSON
	     */
// 	    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// 	        'Content-Type: application/json;charset=utf-8',
// 	        'Content-Length: ' . strlen($data))
// 	        );
	    $output = curl_exec($ch);

	    if (curl_errno($ch)) {
	        echo 'Errno'.curl_error($ch);
	    }
	    curl_close($ch);
	    return $output;
	}
	public function actionIndex123(){
		$this->breadcrumbs = array("Register");
		
		
		if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
		{
			$model=new Customer();
			echo $model->validate();
// 			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		
		if(!isset(Yii::app()->user->id)||Yii::app()->user->id==""){
			$model=new Customer();
			$model=new CustomerInfo();
			$states=State::model()->findAll('country_id=10');
		}else{
			Yii::app()->getRequest()->redirect(Yii::app()->baseUrl);
		}
		if(!empty($_POST)){
			$arr_customer=$_POST['Customer'];
			$arr_info=$_POST['CustomerInfo'];
			$model->user_name=$arr_customer['user_name'];
			$model->password=$arr_customer['password'];
			$model->email=$arr_customer['email'];
			$model->created=time();
			$model->status=1;
			$model->first_name=$arr_info['first_name'];
			$model->last_name=$arr_info['last_name'];
			$model->address=$arr_info['address'];
			$model->city=$arr_info['city'];
			$model->zip_code=$arr_info['zip_code'];
			$model->states=$arr_info['states'];
			$model->phone=$arr_info['phone'];
			$model->BIO=$arr_info['BIO'];
			$model->birthday=$arr_info['birthday'];
			$transaction=$model->dbConnection->beginTransaction();
			try
			{
				$model->save(false);
				$model->id=$model->id;
				$model->save(false);
				$transaction->commit();
			}
			catch(Exception $e)
			{
			    $transaction->rollBack();
			}
			$login_auth=new SysAuth();
			$login_auth->id       =$model->id;
			$login_auth->username = $model->user_name;
			LoginPlus::Login($login_auth);
		}
		$this->render('index123',array('model'=>$model,'model'=>$model,'states'=>$states));
	}
	public static function createUniqid()
	{
	    $tempStr = md5(time());
	    return $tempStr[mt_rand(0,31)].uniqid();
	}
	
	public function actions(){
		return array(
				'captcha'=>array(
				'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
                'maxLength'=>4,       // 最多生成几个字符
                'minLength'=>4,       // 最少生成几个字符
                'testLimit'=>999,
			),

		);
	}
}